<script lang="ts" setup="">
import {onMounted, ref, watchEffect} from 'vue'
import message from '@arco-design/web-vue/es/message'
import { delQuestion, listQuestion } from '@/request/request'
import { useRouter } from 'vue-router'

const show = ref(true)
const loading = ref(false)
const dataList = ref([])
const router = useRouter()
const searchParams = ref({
  pageSize: 5,
  current: 1,
})

const total = ref(0)

const loadData = async () => {
  loading.value = true
  const res = await listQuestion(searchParams.value)
  loading.value = false
  console.log(res.data)
  if (res.data.code === 0) {
    dataList.value = res.data.data.records
    total.value = res.data.data.total
  } else {
    message.error('加载失败' + res.data.message)
  }
}

const doDel = async (question: any) => {
  const res = await delQuestion(question.id)
  if (res.data.code === 0) {
    message.success('删除成功')
    // 更新数据
    await loadData()
  } else {
    message.error('删除失败' + res.data.message)
  }
}

const doModify = (question: any) => {
  router.push({
    path: '/update/question',
    query: {
      id: question.id,
    },
  })
}

const colums = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '标题',
    dataIndex: 'title',
  },
  {
    title: '内容',
    dataIndex: 'content',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '答案',
    dataIndex: 'answer',
  },
  {
    title: '提交数',
    dataIndex: 'submitNum',
  },
  {
    title: '通过数',
    dataIndex: 'acceptedNum',
  },
  {
    title: '判题用例',
    dataIndex: 'judgeCase',
  },
  {
    title: '判题配置',
    dataIndex: 'judgeConfig',
  },
  {
    title: '用户id',
    dataIndex: 'userId',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    slotName: 'optional',
  },
]
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page
  }
}

/**
 * 页面加载时请求数据
 */
onMounted(() => {
  loadData()
})
/**
 * 监听searchParams，在改变时，触发页面的重新加载
 */
watchEffect(() => {
  loadData()
})
</script>

<template>
  <div id="manage-question">
    <h2>管理题目</h2>
    <a-table
      :columns="colums"
      :data="dataList"
      row-class="common-row"
      :loading="loading"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total: total,
      }"
      @page-change="onPageChange"
    >
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doModify(record)">修改</a-button>
          <a-button type="danger" @click="doDel(record)">删除</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<style scoped lang="less"></style>
